<template>
	<view>
		<!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
		<u--form labelPosition="left" :model="form" :rules="rules" ref="uForm" labelWidth="80">
			<u-form-item label="商品类型" prop="goodsType" borderBottom ref="item1">
				<u-radio-group v-model="form.goodsType" placement="row" @change="groupChange">
					<u-radio
						:customStyle="{ marginRight: '30px' }"
						v-for="(item, index) in radiolist1"
						:key="index"
						:label="item.name"
						:name="item.id"
						@change="radioChange"
					></u-radio>
				</u-radio-group>
			</u-form-item>
			<u-form-item label="商品名称" prop="goodsName" borderBottom ref="item1">
				<u--input
					v-model="form.goodsName"
					border="none"
					placeholder="商品名称尽量精简,名称建议不超过20字"
				></u--input>
			</u-form-item>
			<u-form-item label="商品分类" prop="name" borderBottom ref="item1" @click="show = true">
				<u--input
					v-model="form.categoryName"
					disabled
					disabledColor="#ffffff"
					border="none"
					placeholder="请选择商品分类"
				></u--input>
			</u-form-item>
			<u-picker
				:show="show"
				:columns="categoryList"
				keyName="categoryName"
				@confirm="confirm"
				@cancel="show = false"
			></u-picker>
			<u-form-item label="卖点介绍" prop="goodsKeyword" borderBottom ref="item1">
				<u--input
					v-model="form.goodsKeyword"
					border="none"
					placeholder="建议简洁干练的描述出商品特点"
				></u--input>
			</u-form-item>
			<u-form-item label="商品主图" prop="name" borderBottom ref="item1">
				<view
					class=""
					style="display: flex; align-items: center; justify-content: space-between; margin-top: 20rpx"
				>
					<view class="">
						<view class="" style="display: flex; flex-wrap: wrap">
							<image
								v-for="item in form.rotationImgsJson"
								style="
									width: 100rpx;
									height: 100rpx;
									margin-bottom: 20rpx;
									margin-right: 10rpx;
									border-radius: 15rpx;
								"
								:src="item"
								@click="del(index)"
							></image>

							<view
								v-if="form.rotationImgsJson.length < 9"
								@tap="changeImage(2,'rotationImgsJson')"
								style="
									width: 100rpx;
									height: 100rpx;
									background-color: #f5f5f5;
									display: flex;
									justify-content: center;
									align-content: center;
									margin-bottom: 10rpx;
								"
							>
								<u-icon name="photo" size="50"></u-icon>
							</view>
						</view>
					</view>
				</view>
			</u-form-item>
			<u-form-item label="商品视频" prop="name" borderBottom ref="item1">
				<view
					class=""
					style="display: flex; align-items: center; justify-content: space-between; margin-top: 20rpx"
				>
					<view class="">
						<view
							v-if="!form.videoUrl"
							@tap="changeImage(1,'videoUrl')"
							style="
								width: 100rpx;
								height: 100rpx;
								background-color: #f5f5f5;
								display: flex;
								justify-content: center;
								align-content: center;
								margin-bottom: 10rpx;
							"
						>
							<u-icon name="play-circle" size="50"></u-icon>
						</view>
						<view v-else class="" >
							<video
							:controls="true"
								style="
									width: 200rpx;
									height: 200rpx;
									margin-bottom: 20rpx;
									margin-right: 10rpx;
									border-radius: 15rpx;
								"
								:src="form.videoUrl"
								
							></video>
							<u-button style="width: 100rpx;" type="error" size="small" :plain="true" text="删除" @click="delVideoUrl()"></u-button>
						</view>
					</view>
				</view>
			</u-form-item>
			<u-form-item label="商品价格" prop="goodsPrice" borderBottom ref="item1">
				<view class="button" style="display: flex; align-items: center; width: 500rpx">
					<u--input
						v-model="form.goodsPrice"
						border="none"
						placeholder="请输入商品现价(售卖价)"
						:customStyle="{
							border: '1rpx solid #f5f5f5',
							height: '60rpx',
							borderRight: 'none',
							width: '200rpx'   
						}"
					></u--input>
					<view class="btn" v-if="form.goodsType == 0">元</view>
					<view class="btn" v-else>分</view>
				</view>
			</u-form-item>
			<u-form-item label="商品划线价" prop="scribePrice" borderBottom ref="item1">
				<view class="button" style="display: flex; align-items: center; width: 500rpx">
					<u--input
						v-model="form.scribePrice"
						border="none"
						placeholder="请输入商品原价(参考价)"
						:customStyle="{
							border: '1rpx solid #f5f5f5',
							height: '60rpx',
							borderRight: 'none',
							width: '200rpx'
						}"
					></u--input>
					<view class="btn" v-if="form.goodsType == 0">元</view>
					<view class="btn" v-else>分</view>
				</view>
			</u-form-item>
			
			<u-form-item label="库存数量" prop="stockNum" borderBottom ref="item1">
				<view class="button" style="display: flex; align-items: center; width: 500rpx">
					<u--input
						v-model="form.stockNum"
						border="none"
						placeholder="请输入库存数量"
						:customStyle="{
							border: '1rpx solid #f5f5f5',
							height: '60rpx',
							borderRight: 'none',
							width: '200rpx'
						}"
					></u--input>
					<view class="btn">单位</view>
					<!-- <view class="btn">分</view> -->
				</view>
			</u-form-item>
			<!-- <u-form-item label="SKU编号" prop="goodsSkuNumber" borderBottom ref="item1">
				<view class="button" style="display: flex;align-items: center;width: 500rpx;">
					<u--input
						v-model="form.goodsSkuNumber"
						placeholder="请输入SKU编号"
						border="none"
						:customStyle="{ border: '1rpx solid #f5f5f5', height: '60rpx', width: '200rpx' }"
					></u--input>
				</view>
			</u-form-item> -->
			<u-form-item label="商品排序" prop="goodsOrder" borderBottom ref="item1">
				<u--input
					v-model="form.goodsOrder"
					border="none"
					placeholder="排序越大越靠前"
				></u--input>
			</u-form-item>
			<u-form-item label="商品备注" prop="goodsRemarks" borderBottom ref="item1">
				<u--textarea v-model="form.goodsRemarks" placeholder="商品备注,一般不对外显示"></u--textarea>
			</u-form-item>

			<!-- <u-form-item label="所属店铺" prop="name" borderBottom ref="item1" @click="show1 = true">
				<u--input v-model="form.businessName" disabled disabledColor="#ffffff" border="none"></u--input>
			</u-form-item>
			<u-picker :show="show1" :columns="businessList " keyName="businessName" @confirm="confirm1" @cancel="show1 = false"></u-picker>-->
			<!-- <u-form-item label="库存数量" prop="name" borderBottom ref="item1"><u--input v-model="form.name" border="none"></u--input></u-form-item> -->
			<!-- <u-form-item label="运费模版" prop="name" borderBottom ref="item1"><u--input v-model="form.name" border="none"></u--input></u-form-item> -->

			<!-- <u-form-item label="商品排序" prop="name" borderBottom ref="item1"><u--input v-model="form.name" border="none"></u--input></u-form-item> -->
			<view class="footer"><view class="right" @tap="goSku()">设置&修改商品规格>></view></view>
			<view class="footer"><view class="right" @tap="goDetail()">添加&编辑商品详情>></view></view>
			<view class="footer1"><view class="right" @tap="submit()">发布商品</view></view>
		</u--form>
	</view>
</template>

<script>
import {
	uploadImages,
	insertPlugsGoods,
	updatePlugsGoods,
	searchPlugsGoodsById,
	searchPlugsGoodCategoryList,
	getBusinessInfo,
	delPlugsGoodsSpecificationAll,
	insertPlugsGoodsAttributeKey,
	insertPlugsGoodsAttributeValue,
	insertPlugsGoodsSpecification,
	searchPlugsGoodsSpecificationByGoodsId
} from '../../../utils/api.js';
export default {
	data() {
		return {
			showSex: false,
			form: {
				adminId: uni.getStorageSync('userInfo').id,
				userServiceToken: uni.getStorageSync('userInfo').userServiceToken,
				plugsId: 141,
				consumePersonNum: '',
				effectDays: '',
				examineStatus: 1,
				extJson: '',
				goodsBeginTime: '',
				goodsDetails: '',
				goodsDetailsJson: '',
				goodsEndingTime: '',
				goodsName: '',
				goodsPrice: '',
				goodsStatus: 0,
				goodsType: 0,
				goodsViewCount: '',
				goodsWeight: 0,
				id: '',
				limitNum: '100',
				monthSales: '',
				businessId: -1,
				categoryId: -1,
				previewUrl: '',
				retirementRule: '',
				rewardIntegral: '',
				distributionFee: '',
				rotationImgsJson: [],
				scribePrice: '',
				shareJson: '',
				stockNum: '1000',
				totalSales: '',
				useRuleJson: '',
				memberPrice: '',
				packingFee: '',
				businessName: '',
				goodsSkuNumber: '',
				goodsRemarks: '',
				goodsKeyword: '',
				videoUrl:'',
				goodsOrder:''
			},
			radiolist1: [
				{
					name: '普通商品',
					id: 0,
					disabled: false
				},
				{
					name: '积分商品',
					id: 1,
					disabled: false
				}
			],

			rules: {
				'form.name': {
					type: 'string',
					required: true,
					message: '请填写姓名',
					trigger: ['blur', 'change']
				},
				'form.sex': {
					type: 'string',
					max: 1,
					required: true,
					message: '请选择男或女',
					trigger: ['blur', 'change']
				}
			},
			radio: '',
			switchVal: false,
			show: false,
			show1: false,
			categoryList: [[]],
			attribute: [],
			tableData: [],
			arrLsit:[]
		};
	},
	onLoad(option) {
		console.log(option.id);
		this.form.id = option.id;
		let that = this;
		uni.$on('goodsDetailsJson', function (data) {
			if (data != null) {
				console.log(data,123);
				that.form.goodsDetailsJson = data;
				console.log(that.form.goodsDetailsJson, 'pppppppppppppppp');
			}
		});
		uni.$on('skuData', function (attribute, tableData) {
			if (attribute != null) {
				// that.form.goodsDetailsJson = data;
				that.attribute = attribute;
				that.tableData = tableData;
				console.log(that.tableData, 'pppppppppppppppp');
			} else {
				that.attribute = [];
				that.tableData = [];
				console.log(that.attribute, that.tableData, 'sadfasdasd');
			}
		});
		this.getForm()
		
	},
	onShow() {
		
		this.getCategoryList();
		
		uni.$once('rotationImgsJson', (data) => {
			console.log(data, 1231239966);
			if (data.length > 0) {
				this.form.rotationImgsJson = data;
				console.log(this.form.rotationImgsJson,9666645);
			}
		});
		uni.$once('videoUrl', (data) => {
			console.log(data, 1231239966);
			if (data.length > 0) {
				this.form.videoUrl = data[0];
				console.log(this.form.videoUrl,9666645);
			}
		});
	},
	methods: {
		groupChange(n) {
			console.log('groupChange', n);
		},
		radioChange(n) {
			console.log('radioChange', n);
		},
		confirm(e) {
			console.log(e);
			this.form.categoryId = e.value[0].id;
			this.form.categoryName = e.value[0].categoryName;
			this.form.businessId = e.value[0].businessId;
			this.form.businessName = e.value[0].businessName;
			this.show = false;
		},
		confirm1(e) {
			this.form.businessId = e.value[0].businessId;
			this.form.businessName = e.value[0].businessName;
			this.show1 = false;
		},
		getForm(){
			if (this.form.id) {
				let data = {
					id: this.form.id
				};
				searchPlugsGoodsById(data).then((result) => {
					if (result.code == 200) {
						this.form = result.body;
						if(this.form.rotationImgsJson){
							this.form.rotationImgsJson = JSON.parse(this.form.rotationImgsJson);
						}else{
							this.rotationImgsJson=[]
						}
						let data = {
							goodsId: this.form.id
						};
						searchPlugsGoodsSpecificationByGoodsId(data).then((res) => {
							if (res.code == 200) {
								if (res.body.specificationInfo.length !== 0) {
									let arr = [];
									this.specificationInfo = res.body.specificationInfo;
									for (let item of res.body.specificationInfo) {
										let obj1 = {
											name: Object.keys(item)[0],
											value: [],
											title: '',
											show: false,
											children: Object.values(item)[0]
										};
										console.log(item, 456);
										arr.push(obj1);
									}
									arr.forEach((item) => {
										console.log(item.children, 7777);
										item.children.forEach((ress) => {
											console.log(ress.attributeValue);
											item.value.push(ress.attributeValue);
										});
									});
									console.log(arr, 789);
									this.attribute = arr;
									let arr1 = [];
									res.body.plugsGoodsSpecificationList.forEach((item) => {
										let obj2 = {
											specificationName: item.specificationName,
											scribePrice: item.scribePrice,
											dealPrice: item.dealPrice,
											stockNum: item.stockNum,
											specificationNumber: item.specificationNumber,
											specificationImages: item.specificationImages,
											position: item.position
										};
										arr1.push(obj2);
									});
									this.tableData = res.body.plugsGoodsSpecificationList;
								}
							}
						});
					}
				});
			}
		},
		getCategoryList() {
			this.categoryList = [[]];
			let data = {
				page: 1,
				size: 100,
				adminId: uni.getStorageSync('userInfo').id,
				userServiceToken: uni.getStorageSync('userInfo').userServiceToken,
				id: 141,
				businessId: -1
			};
			searchPlugsGoodCategoryList(data).then((res) => {
				if (res.code == 200) {
					// this.categoryList[0]=res.body.list
					// res.body.list.forEach((item) => {
					// 	this.categoryList[0].push(item);
					// });
					let arr = [];
					// arr = this.categoryList.concat(res.body.list);
					// this.categoryList = arr;
					res.body.list.forEach((item) => {
						this.arrLsit.push(item);
						if (item.pgoodCategoryList.length > 0) {
							item.pgoodCategoryList.forEach((item1) => {
								this.arrLsit.push(item1);
								if (item1.pgoodCategoryList.length > 0) {
									item1.pgoodCategoryList.forEach((item2) => {
										this.arrLsit.push(item2);
										if (item2.pgoodCategoryList.length > 0) {
											item2.pgoodCategoryList.forEach((item3) => {
												this.arrLsit.push(item3);
												if (item3.pgoodCategoryList.length > 0) {
													item3.pgoodCategoryList.forEach((item4) => {
													});
												}
											});
										}
									});
								}
							});
						}
					});
					
					this.arrLsit.forEach((item,index)=>{
						if(item.pgoodCategoryList.length==0){
							item.categoryName=item.categoryName+'----'+item.businessName
							this.categoryList[0].push(item)
						}
					})
					
				}
			});
		},
		
		goSku() {
			uni.navigateTo({
				url: '/pages/goods/goodsAdd/sku/sku?id=' + this.form.id
			});
		},
		changeImage(index,name) {
			// let that = this;
			// uni.chooseImage({
			// 	count: 9, //默认9
			// 	sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			// 	sourceType: ['album'], //从相册选择
			// 	loop: true,
			// 	success: res => {
			// 		console.log(res);
			// 		let data = {
			// 			file: res.tempFilePaths, //你要传的临时文件
			// 			type: 1
			// 		};
			// 		uploadImages(data).then(ress => {
			// 			if (ress.code == 200) {
			// 				form.rotationImgsJson = ress.body;
			// 			}
			// 		});
			// 	}
			// });
			uni.navigateTo({
				url: `/pages/user/annex/annex?source=${index}&type=${name}`
			});
		},
		del(index) {
			let that = this;
			uni.showModal({
				title: '提示',
				content: '您确定要删除此图片吗？',
				cancelText: '取消', // 取消按钮的文字
				confirmText: '确定', // 确认按钮文字
				showCancel: true, // 是否显示取消按钮，默认为 true
				// confirmColor: '#f55850',
				// cancelColor: '#39B54A',
				success: (res) => {
					if (res.confirm) {
						//点击了确定
						this.form.rotationImgsJson.splice(index, 1);
						uni.showToast({
							icon: 'none',
							title: '删除成功'
						});
					} else {
						//点击了取消
					}
				}
			});
		},
		delVideoUrl(){
			let that = this;
			uni.showModal({
				title: '提示',
				content: '您确定要删除此视频吗？',
				cancelText: '取消', // 取消按钮的文字
				confirmText: '确定', // 确认按钮文字
				showCancel: true, // 是否显示取消按钮，默认为 true
				// confirmColor: '#f55850',
				// cancelColor: '#39B54A',
				success: (res) => {
					if (res.confirm) {
						//点击了确定
						this.form.videoUrl='';
						uni.showToast({
							icon: 'none',
							title: '删除成功'
						});
					} else {
						//点击了取消
					}
				}
			});
		},
		goDetail() {
			uni.navigateTo({
				url: `/pages/goods/goodsAdd/detail?goodsDetailsJson=${encodeURIComponent(JSON.stringify(this.form.goodsDetailsJson))} `
			});
		},
		submit() {
			console.log(this.form.id);
			if (!this.form.goodsName) {
				uni.showModal({
					title: '提示',
					content: '请输入商品名称',
					success(res) {}
				});

				return;
			} else if (!this.form.categoryName) {
				uni.showModal({
					title: '提示',
					content: '请选择商品分类',
					success(res) {}
				});

				return;
			} else if (this.form.rotationImgsJson.length == 0) {
				uni.showModal({
					title: '提示',
					content: '请上传商品主图',
					success(res) {}
				});

				return;
			} else if (!this.form.goodsPrice) {
				uni.showModal({
					title: '提示',
					content: '请输入商品价格',
					success(res) {}
				});

				return;
			}

			this.form.rotationImgsJson = JSON.stringify(this.form.rotationImgsJson);
			let that = this;
			if (!that.form.id || that.form.id == '') {
				insertPlugsGoods(that.form).then((res) => {
					if (res.code == 200) {
						console.log(that.attribute, 789);

						if (that.tableData.length !== 0) {
							let data = {
								goodsIdList: [res.body[0].id],
								plugsGoodsSpecificationList: that.tableData
							};
							insertPlugsGoodsSpecification(data).then((res1) => {});
						} else {
						}

						uni.showToast({
							icon: 'success',
							title: '添加成功'
						});
						setTimeout(() => {
							uni.navigateBack({ delta: 1 });
						}, 500);
					}
				});
			} else {
				updatePlugsGoods(that.form).then((res) => {
					if (res.code == 200) {
						if (that.tableData.length !== 0) {
							delPlugsGoodsSpecificationAll({ goodsId: that.form.id }).then((res1) => {
								if (res1.code == 200) {
									let data = {
										goodsIdList: [that.form.id],
										plugsGoodsSpecificationList: that.tableData
									};
									insertPlugsGoodsSpecification(data).then((res2) => {});
								}
							});
						} else {
							delPlugsGoodsSpecificationAll({ goodsId: that.form.id });
						}

						uni.showToast({
							icon: 'success',
							title: '修改成功'
						});
						setTimeout(() => {
							uni.navigateBack({ delta: 1 });
						}, 500);
					}
				});
			}
		}
	},
	onReady() {
		//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
		this.$refs.uForm.setRules(this.rules);
	}
};
</script>
<style lang="scss">
page {
	padding: 20rpx;
	box-sizing: border-box;
}
.btn {
	width: 60rpx;
	color: #fff;
	height: 60rpx;
	line-height: 60rpx;
	font-size: 26rpx;
	background-color: #6da7ff;
	text-align: center;
}
.footer {
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #fff;
	width: 100%;
	margin: 10rpx 0;
	.right {
		background-color: #eff6ff;
		border: 1rpx solid #d1e5ff;
		// padding: 20rpx;
		border-radius: 40rpx;
		color: #016eff;
		width: 500rpx;
		height: 80rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}
}
.footer1 {
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #fff;
	width: 100%;
	margin: 10rpx 0;
	.right {
		background-color: #016eff;
		border: 1rpx solid #d1e5ff;
		// padding: 20rpx;
		border-radius: 40rpx;
		color: #fff;
		width: 500rpx;
		height: 80rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}
}
</style>
